package com.duan.laugh.common.core.exception;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.duan.laugh.common.core.constants.CoreConstants;
import com.duan.laugh.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @author duanjw
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常
     *
     * @param e 异常
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public R exception(Exception e) {
        log.info("保存全局异常信息 ex={}", e.getMessage(), e);
        return new R(e);
    }

    /**
     * 全局自定义runtime异常
     * 返回200的状态码
     *
     * @param e 异常
     * @return R
     */
    @ExceptionHandler(BaseRuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public R exception(BaseRuntimeException e) {
        String message = e.getMessage();
        String[] msg = StrUtil.split(message, CoreConstants.CODE_MESSAGE_SPLIT);
        R r = new R<>();
        if (msg.length >= CoreConstants.TWO && NumberUtil.isInteger(msg[CoreConstants.ZERO])) {
            r.setMsg(msg[CoreConstants.ONE]);
            r.setCode(Integer.parseInt(msg[CoreConstants.ZERO]));
        } else {
            r.setMsg(e.getMessage());
            r.setCode(e.getCode());
        }
        log.error("保存全局【自定义运行时异常】信息 ex={}", e.getMessage(), e);
        return r;
    }

    /**
     * 参数校验失败异常
     *
     * @param e 异常
     * @return R
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R handle(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        R result = new R();
        result.setCode(R.FAIL);
        result.setMsg(bindingResult.getFieldError().getDefaultMessage());
        return result;
    }
}
